package dao;

import modle.JDBCUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    private Connection connection = null;
    /**
     * 0代表数据库出现错误，1代表无用户（账号密码有问题），2代表成功
     */
    public int checkAccount(String type,String uAcc, String uPwd) {
        PreparedStatement pstmt = null;//声明一个PreparedStatement对象并将其初始化为null
        String sql = "select * from Login_Account where QXtype = ? and Account = ? and Password = ?";//参数占位符
        ResultSet rs = null;
        int result = 0,status = 0;
        try{
            connection = JDBCUtil.getConn();
            pstmt = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            //ResultSet.TYPE_SCROLL_INSENSITIVE：游标可以前后移动，结果集对创建结果集后其他人对数据库所做的更改不敏感
            // 结果集是只读的，这是默认的并发类型
            pstmt.setString(1, type);
            pstmt.setString(2, uAcc);
            pstmt.setString(3, uPwd);
            rs = pstmt.executeQuery();
            rs.last();//将游标移动到结果集中的最后一行
            result = rs.getRow();//获取结果集中当前行的行号，即结果集的行数
            pstmt.close();
            connection.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
        catch (NullPointerException e){
            return status;
        }finally{
            try{
                if (connection != null && (!connection.isClosed())){
                    connection.close();
                }
            }catch(SQLException e){
                //e.printStackTrace();
            }
        }
        if(result > 0)
            status = 2;
        else
            status = 1;
        return status;
    }

    public boolean setPassword(String type,String uAcc, String uPwd) {
        PreparedStatement pstmt = null;//声明一个PreparedStatement对象并将其初始化为null
        String sql = "UPDATE Login_Account SET Password = ? WHERE QXtype = ? and Account = ?";//参数占位符
        ResultSet rs = null;
        JDBCUtil db = new JDBCUtil();
        int result = 0,status = 0;
        try{
            connection = db.getConn();
            pstmt = connection.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
            //ResultSet.TYPE_SCROLL_INSENSITIVE：游标可以前后移动，结果集对创建结果集后其他人对数据库所做的更改不敏感
            // 结果集是只读的，这是默认的并发类型
            pstmt.setString(1, uPwd);
            pstmt.setString(2, type);
            pstmt.setString(3, uAcc);
            pstmt.executeUpdate();
            pstmt.close();
            connection.close();
        }catch (SQLException e) {
            //e.printStackTrace();
        }
        catch (NullPointerException e){
            return false;
        }finally{
            try{
                if (connection != null && (!connection.isClosed())){
                    connection.close();
                }
            }catch(SQLException e){
                //e.printStackTrace();
            }
        }
        return true;
    }
}